package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrdersService ordersService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpSession session) {
        log.info("订单数据: {}", orders);
        ordersService.submit(orders, session);
        return R.success("下单成功");
    }

    /**
     * 查看订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize, HttpSession session) {
        Page<OrdersDto> page1 = new Page<>(page, pageSize);

        Page<Orders> pageInfo = new Page<>();
        Long userId = (Long) session.getAttribute("user");

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId);
        queryWrapper.orderByDesc(Orders::getOrderTime);

        ordersService.page(pageInfo, queryWrapper);
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> records2 = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();

            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> list = orderDetailService.list(wrapper);
            int sumNum = 0;
            for (OrderDetail orderDetail : list)
                sumNum += orderDetail.getNumber();

            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setSumNum(String.valueOf(sumNum));

            return ordersDto;
        }).collect(Collectors.toList());

        page1.setRecords(records2);
        return R.success(page1);
    }

    /**
     * 后台查看订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(int page, int pageSize, String number, String beginTime, String endTime) {
        log.info("{} {} {} {} {}", page, pageSize, number, beginTime, endTime);
        Page < Orders > pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(number != null, Orders::getId, number);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        if (beginTime != null && endTime != null) {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            queryWrapper.between(Orders::getOrderTime, LocalDateTime.parse(beginTime, df), LocalDateTime.parse(endTime, df));
        }

        ordersService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 派送订单
     * @return
     */
    @PutMapping
    public R<String> send(@RequestBody Orders orders){
        Orders one = ordersService.getById(orders);
        one.setStatus(4);
        ordersService.updateById(one);
        return R.success("订单已送达!");
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        log.info("{}", orders);
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
        Long currentId = BaseContext.getCurrentId();

        List<ShoppingCart> shoppingCarts = list.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(currentId);
            if (item.getDishId() != null) {
                shoppingCart.setDishId(item.getDishId());
                shoppingCart.setDishFlavor(item.getDishFlavor());
            } else
                shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setName(item.getName());
            shoppingCart.setAmount(item.getAmount());
            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCarts.forEach((item)->{
            Long dishId = item.getDishId();
            LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();

            wrapper.eq(ShoppingCart::getUserId, currentId);
            if (dishId == null)
                wrapper.eq(ShoppingCart::getSetmealId, item.getSetmealId());
            else
                wrapper.eq(ShoppingCart::getDishId, item.getDishId());

            ShoppingCart shoppingCart = shoppingCartService.getOne(wrapper);
            if (shoppingCart == null)
                shoppingCartService.save(item);
            else {
                shoppingCart.setNumber(shoppingCart.getNumber() + item.getNumber());
                shoppingCartService.updateById(shoppingCart);
            }
        });
        return R.success("再来一单成功");
    }
}
